package com.example.flowershop.adapter;


import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.example.flowershop.R;
import com.example.flowershop.entity.Stuff;

import java.util.List;

public class StuffAdapter extends ArrayAdapter<Stuff> {

    public StuffAdapter(@NonNull Context context, int resource, @NonNull List<Stuff> objects) {
        super(context, resource, objects);
    }

    /**
     * 每个子项被滚动到屏幕内的时候会被调用
     */
    @NonNull
    @Override
    public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
        //得到当前项的 Stuff 实例
        Stuff item = getItem(position);
        ViewHolder holder = ViewHolder.getViewHolder(convertView, parent);

        Glide.with(holder.ivPic).load(item.getPic()).into(holder.ivPic);
        holder.tvName.setText(item.getName());
        holder.tvInfo.setText(item.getInfo());
        holder.tvCount.setText("库存：" + item.getCount());
        holder.tvPrice.setText(String.format("¥%.2f", item.getPrice()));

        holder.ivPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(getContext(), item.getName(), Toast.LENGTH_SHORT).show();
            }
        });
        return holder.getView();
    }

    public void setData(List<Stuff> stuffList) {
        clear();
        addAll(stuffList);
        notifyDataSetChanged();
    }

    public static class ViewHolder {

        private final View convertView;
        public ImageView ivPic;
        public TextView tvName, tvInfo, tvCount, tvPrice;

        public ViewHolder(@Nullable View convertView, @NonNull ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_stuff, parent, false);
            }
            this.convertView = convertView;
            ivPic = convertView.findViewById(R.id.iv_pic);
            tvName = convertView.findViewById(R.id.tv_name);
            tvInfo = convertView.findViewById(R.id.tv_info);
            tvCount = convertView.findViewById(R.id.tv_count);
            tvPrice = convertView.findViewById(R.id.tv_price);
        }

        public static ViewHolder getViewHolder(@Nullable View convertView, @NonNull ViewGroup parent) {
            return new ViewHolder(convertView, parent);
        }

        public View getView() {
            return convertView;
        }

    }
}
